package servlet.sessionDemo;

import utils.TimeUtil;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 *
 * servlet
 * Session 管理
 *
 * M：使用cookie技术，显示Session的管理
 * M：实际上，使用了cookie技术，即使用户关闭了浏览器，数据也还是可以会有的。
 * 2018/5/15-7:36
 * 2018
 * Created by wuqiang on 2018/5/15.
 */
public class CookiesDemo extends HttpServlet {
    /**
     * 显示用户上次访问的时间
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        PrintWriter writer = resp.getWriter();
        writer.print("上次访问时间：");
        Cookie[] cookies = req.getCookies();//所有的请求数据都会封装在req对象中
        if(cookies!=null){
            for(Cookie cookie:cookies){//
                if("lastAccessTime".equals(cookie.getName())){
                    long l = Long.parseLong(cookie.getValue());
                    Date date = new Date(l);
                    writer.println("cookie的path"+cookie.getPath());
                    writer.print(TimeUtil.parseDateTime2String(date));
                    break;
                }
            }
        }
        //更新cookie最新时间
        Cookie cookie=new Cookie("lastAccessTime",System.currentTimeMillis()+"");
        cookie.setMaxAge(3600);
        cookie.setPath("/cookie2.do");
        resp.addCookie(cookie);
    }
}
